//
//  CZPhotoSelectorViewController.swift
//  照片选择器
//
//  Created by zhangping on 15/10/22.
//  Copyright © 2015年 zhangping. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class CZPhotoSelectorViewController: UICollectionViewController {
    // MARK: - 属性
    /// 当前点击cell的indexPath
    private var currentIndexPath: NSIndexPath?
    
    /// 最大图片张数
    private let maxPhotoCount = 6
    
    /// 选择的图片
    var photos = [UIImage]()
    
    /// collectionView 的流水布局
    private var layout = UICollectionViewFlowLayout()
    
    // MARK: - 构造函数
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 构造函数
    init() {
        super.init(collectionViewLayout: layout)
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        // 注册cell
        collectionView!.registerClass(CZPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        // 设置背景
        collectionView?.backgroundColor = UIColor.whiteColor()
        
        // 设置itemSize
        layout.itemSize = CGSize(width: 80, height: 80)
        
        // 设置每组的边距
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 1.photos.count < maxPhotoCount 显示 photos.count + 1
        // 2.photos.count = maxPhotoCount 显示 photos.count
        return photos.count < maxPhotoCount ? photos.count + 1 : photos.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CZPhotoSelectorCell
    
        cell.backgroundColor = UIColor.brownColor()
        
        // 设置代理
        cell.cellDelegate = self
        
        // 如果有照片,设置cell显示image
        if indexPath.item < photos.count {
            cell.image = photos[indexPath.row]
        } else {
            cell.image = nil
        }
        
        return cell
    }
}

// MARK: - 扩展 CZPhotoSelectorViewController 实现 CZPhotoSelectorCellDelegate 协议
extension CZPhotoSelectorViewController: CZPhotoSelectorCellDelegate {
    /// 添加图片
    func photoSelectorCellAddPhoto(cell: CZPhotoSelectorCell) {
        // 判断用户是否同意应用访问相册
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("用户不允许访问相册")
            return
        }
        
        // 弹出系统相册
        let picker = UIImagePickerController()
        
        // 设置代理
        picker.delegate = self
        
        // 将点击的cell的indexPath记录下来
        currentIndexPath = collectionView?.indexPathForCell(cell)
        
        presentViewController(picker, animated: true, completion: nil)
    }
    
    /// 删除图片
    func photoSelectorCellRemovePhoto(cell: CZPhotoSelectorCell) {
        // 获取cell的indexPath
        if let indexPath = collectionView?.indexPathForCell(cell) {
            // 删除 photos 数组中对应的 iamge
            photos.removeAtIndex(indexPath.item)
            
            // 刷新数据
            collectionView?.reloadData()
        }
    }
}

// MARK: - CZPhotoSelectorViewController 实现 UIImagePickerControllerDelegate UINavigationControllerDelegate 协议.获取选取的图片
extension CZPhotoSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    /// 选中图片时调用, 一旦实现这个方法,需要主动关闭控制器
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // 获取到图片
        let newImage = image.scaleImage()
        print("image: \(newImage)")
        
        // 点击加号表示添加图片.
        // 点击图片表示替换图片
        
        // 点击加号按钮
        if currentIndexPath?.item == photos.count {
            // 将选中的图片添加到图片数组
            photos.append(newImage)
        } else {
            // 替换图片
            photos[currentIndexPath!.item] = newImage
        }
        
        // collectionView 刷新数据
        collectionView?.reloadData()
        
        // 关闭系统相册控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - cell的点击事件协议
protocol CZPhotoSelectorCellDelegate: NSObjectProtocol {
    // 加号按钮点击事件
    func photoSelectorCellAddPhoto(cell: CZPhotoSelectorCell)
    
    // 删除按钮点击时间
    func photoSelectorCellRemovePhoto(cell: CZPhotoSelectorCell)
}

/// 自定义cell
class CZPhotoSelectorCell: UICollectionViewCell {
    
    // MARK: - 属性
    /// 显示的image
    var image: UIImage? {
        didSet {
            // image == nil 表示最后一个按钮
            if image == nil {
                addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            } else {
                addButton.setImage(image, forState: UIControlState.Normal)
            }
            
            // 如果是最后一个按钮不需要显示删除按钮
            removeButton.hidden = image == nil
        }
    }
    
    /// 代理
    weak var cellDelegate: CZPhotoSelectorCellDelegate?
    
    // MARK: - 构造函数
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }

    // MARK: - 准备UI
    /// 准备UI
    private func prepareUI() {
        // 添加子控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        // 添加约束
        // 作为独立工程最好少依赖第三方框架
        addButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDicts = ["ab": addButton, "rb": removeButton]
        // 添加按钮
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDicts))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDicts))
        
        // 删除按钮
        // 水平方向在父控件右边一定距离
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDicts))
        
        // 垂直方向在父控件顶部一定距离
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDicts))
    }
    
    // MARK: - 按钮点击事件
    /// 加号按钮点击事件
    func addButtonClick() {
        cellDelegate?.photoSelectorCellAddPhoto(self)
    }
    
    /// 删除按钮点击事件
    func removeButtonClick() {
        cellDelegate?.photoSelectorCellRemovePhoto(self)
    }
    
    // MARK: - 懒加载控件
    /// 加号按钮
    private lazy var addButton: UIButton = {
        let button = UIButton()
        
        // 设置按钮图片
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        
        // 设置图片的填充模式
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        // 添加点击事件
        button.addTarget(self, action: "addButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    /// 删除按钮
    private lazy var removeButton: UIButton = {
        let button = UIButton()
        
        // 添加图片
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        // 添加点击事件
        button.addTarget(self, action: "removeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}

// MARK: - UIImage扩展,等比例缩小图片到指定的宽度
extension UIImage {
    
    /**
    等比例缩小图片到指定的宽度
    - parameter newWidth: 缩放后的宽度
    - newWidth 默认等于 300
    */
    func scaleImage(newWidth: CGFloat = 300) -> UIImage {
        // 如果图片宽度小于 newWidth, 直接返回
        if size.width < newWidth {
            return self
        }
        
        // 计算缩放好后的高度
        // newHeight / newWidth = height / width
        let newHeight = newWidth * size.height / size.width
        
        let newSize = CGSize(width: newWidth, height: newHeight)
        
        // 将图片等比例缩放到 newSize
        
        // 开启图片上下文
        UIGraphicsBeginImageContext(newSize)
        
        // 绘图
        drawInRect(CGRect(origin: CGPoint(x: 0, y: 0), size: newSize))
        
        // 获取绘制好的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // 关闭绘图上下文
        UIGraphicsEndImageContext()
        
        // 返回绘制好的新图
        return newImage
    }
}